import java.sql.ResultSet;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.Blob;
import javax.imageio.ImageIO;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JList;
import javax.swing.Timer;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * UserProfile.java
 *
 * Created on Apr 12, 2012, 1:42:10 PM
 */

/**
 *
 * @author jacobsm
 */
public class UserProfile extends javax.swing.JPanel {
    Controller controls;
    DatabaseConnection dbConnect;
	Timer refreshTimer;
	
    /** Creates new form UserProfile */
    public UserProfile(Controller control, DatabaseConnection db) {
        this.controls = control;
        this.dbConnect = db;
        initComponents();
        
        userGameList.setListData(new Object[]{});
		
		refreshTimer = new javax.swing.Timer(2000, new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent evt) {
				updateGamesList();
			}
		});
		refreshTimer.setRepeats(true);
    }

    /**
       Changes the profiles information given a username to look up
    **/
    public void getInformation(String username) {
        String selectQuery = String.format(
                "SELECT email, description FROM user WHERE username = '%s'",
                username
        );
        ResultSet user = dbConnect.executeQuery(selectQuery);
        this.setUsername(username);
        try {
            user.next();
            String email = user.getString(1);
            String description = user.getString(2);
            this.setEmail(email);
            this.setDescription(description);
			refreshTimer.start();
        }
        catch (SQLException e) {
            System.err.println("");
        }
    }

    public void updateStats() {
        String getStatsQuery = String.format(
                "SELECT * FROM user_stats WHERE username='%s'",
                usernameLabel.getText()
        );
        
        dbConnect.connect();
        ResultSet stats = dbConnect.executeQuery(getStatsQuery);
        
        if (stats != null) {
            try {
                stats.next();
                numWinsLabel.setText(Integer.toString(stats.getInt(2)));
                numLossesLabel.setText(Integer.toString(stats.getInt(3)));
            } catch (SQLException e) {
                // TODO Handle failure.
                System.err.println("Failed to get user's stats.");
            } finally {
                dbConnect.closeConnection();
            }
        }
        else {
            numWinsLabel.setText("0");
            numLossesLabel.setText("0");
        }
    }

    public void updateGamesList() {        
        if (!controls.username.equals(usernameLabel.getText())) {
            return;
        }
		
        userGameList.setListData(new Object[]{});
        
        String getGamesQuery = String.format(
                "SELECT * FROM game_state WHERE user1='%s' OR user2='%s'",
                controls.username, controls.username
        );
        dbConnect.connect();
        ResultSet games = dbConnect.executeQuery(getGamesQuery);
        
        if (games != null) try {
            String gameItemFmt = "User: %s   State: %s";
            ArrayList<String> gameItems = new ArrayList<String>();
            
            while (games.next()) {
                String gameState = null;
                String gameOpponent = null;

                if (usernameLabel.getText().equals(games.getString(1))) {
                    gameState = games.getInt(4) == 1 ? games.getString(3) : "wait";
                    gameOpponent = games.getString(2);
                }
                else {
                    gameState = games.getInt(4) == 2 ? games.getString(3) : "wait";
                    gameOpponent = games.getString(1);
                }
                
                gameItems.add(String.format(gameItemFmt, gameOpponent, gameState));
            }
            userGameList.setListData(gameItems.toArray());
			
			if (!refreshTimer.isRunning()) {
				refreshTimer.start();
			}
        }
        catch (SQLException e) {
            // TODO Handle failure.
            System.err.println("Failed to query user's game list: " + e.getLocalizedMessage());
        }
        finally {
            dbConnect.closeConnection();
        }
    }
	
    /**
        Sets the username label to be correct
    **/
    public void setUsername(String username) {
        this.usernameLabel.setText(username);
    }

    /**
        Sets the email label to be correct
    **/
    public void setEmail(String email) {
        this.userEmailTextField.setText(email);
    }

    /**
        Sets the email label to be correct
    **/
    public void setDescription(String description) {
        this.userDescriptionTextPane.setText(description);
    }

    public void setProfilePicture(BufferedImage pic) {
        if (pic != null) {
            Image scaledImage = pic.getScaledInstance(
                    200, 200, Image.SCALE_DEFAULT);

            avatarLabel.setIcon(new javax.swing.ImageIcon(scaledImage));
        }
    }
    
    public void setProfilePicture(Blob pic) throws SQLException{
        if(pic != null){
            try {
                BufferedImage image = ImageIO.read(pic.getBinaryStream());
                Image scaledImage = image.getScaledInstance(
                        200, 200, Image.SCALE_DEFAULT
                );
                
                avatarLabel.setIcon(new javax.swing.ImageIcon(scaledImage));

            } catch (IOException ex) {
                System.out.println("Profile picture could not be read.");
            }
        }
    }
    
    private void saveProfileChanges(){
        String userEmail = userEmailTextField.getText();
        String userDescription = userDescriptionTextPane.getText();
        String username = usernameLabel.getText();
        
        String updateQuery = String.format("UPDATE user SET email = '%s', " +
                "description = '%s' WHERE username = '%s';", 
                userEmail, userDescription, username);
        
        int result = dbConnect.executeUpdate(updateQuery);
        if(result != -1)
            System.out.println("Profile changes saved");
        else
            System.out.println("Could not save profile changes to the database.");
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        bannerLabel = new javax.swing.JLabel();
        userInfoPanel = new javax.swing.JPanel();
        avatarLabel = new javax.swing.JLabel();
        usernameLabel = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        numWinsLabel = new javax.swing.JLabel();
        numLossesLabel = new javax.swing.JLabel();
        userEmailTextField = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        userGameList = new javax.swing.JList();
        jLabel8 = new javax.swing.JLabel();
        friendsButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        userDescriptionTextPane = new javax.swing.JTextPane();
        UserOptionsLabel = new javax.swing.JLabel();
        saveButton = new javax.swing.JButton();

        setBackground(new java.awt.Color(0, 102, 153));

        bannerLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        bannerLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/draw-something-logo.jpg"))); // NOI18N
        bannerLabel.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        avatarLabel.setBackground(new java.awt.Color(255, 255, 255));
        avatarLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/empty_profile_picture.gif"))); // NOI18N
        avatarLabel.setText("jLabel1");
        avatarLabel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        avatarLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                avatarLabelMouseClicked(evt);
            }
        });

        usernameLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        usernameLabel.setForeground(new java.awt.Color(0, 0, 255));
        usernameLabel.setText("Username");
		
		userGameList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                userGameListMouseClicked(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel3.setText("Wins:");

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel4.setText("Losses:");

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel5.setText("Email:");

        numWinsLabel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        numWinsLabel.setText("numWins");

        numLossesLabel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        numLossesLabel.setText("numLosses");

        userEmailTextField.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        userEmailTextField.setText("userEmail");

        javax.swing.GroupLayout userInfoPanelLayout = new javax.swing.GroupLayout(userInfoPanel);
        userInfoPanel.setLayout(userInfoPanelLayout);
        userInfoPanelLayout.setHorizontalGroup(
            userInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(userInfoPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(avatarLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(userInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(userInfoPanelLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(userInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(userInfoPanelLayout.createSequentialGroup()
                                .addGroup(userInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel3))
                                .addGap(18, 18, 18))
                            .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 94, Short.MAX_VALUE))
                        .addGroup(userInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(numLossesLabel)
                            .addComponent(numWinsLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(userEmailTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(userInfoPanelLayout.createSequentialGroup()
                        .addGap(71, 71, 71)
                        .addComponent(usernameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        userInfoPanelLayout.setVerticalGroup(
            userInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(userInfoPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(userInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(userInfoPanelLayout.createSequentialGroup()
                        .addComponent(usernameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(userInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(userEmailTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(userInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(numWinsLabel))
                        .addGap(15, 15, 15)
                        .addGroup(userInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(numLossesLabel)))
                    .addComponent(avatarLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 21, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 445, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 9, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 445, Short.MAX_VALUE)
        );

        userGameList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Game 1", "Game 2", "Game 3", "Game 4", "Game 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(userGameList);

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel8.setForeground(new java.awt.Color(255, 255, 255));
        jLabel8.setText(" Current Games");

        friendsButton.setText("See Friends");
        friendsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                friendsButtonActionPerformed(evt);
            }
        });

        userDescriptionTextPane.setText("User description here.");
        jScrollPane1.setViewportView(userDescriptionTextPane);

        UserOptionsLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        UserOptionsLabel.setForeground(new java.awt.Color(255, 255, 255));
        UserOptionsLabel.setText("User Options");

        saveButton.setText("Save");
        saveButton.setToolTipText("");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 657, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(userInfoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(6, 6, 6)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addComponent(bannerLabel)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(UserOptionsLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(32, 32, 32))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(friendsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(24, 24, 24))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(bannerLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 109, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(UserOptionsLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(friendsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(17, 17, 17)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel8)
                                .addGap(18, 18, 18)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(userInfoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(8, 8, 8)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE)))
                .addContainerGap())
        );
    }// </editor-fold>                        

    private void friendsButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              
        this.controls.openFriendsList();
    }                                             

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        saveProfileChanges();
    }                                          

    private void avatarLabelMouseClicked(java.awt.event.MouseEvent evt) {                                         
        controls.openPictureUploader(usernameLabel.getText());
    }                                        
	
	private void userGameListMouseClicked(java.awt.event.MouseEvent evt) {
		// smithre5: Yes, this is stupid and brittle.
		
		if (evt.getClickCount() == 2) {
			JList gameList = (JList)evt.getSource();
			String gameItem = (String)gameList.getSelectedValue();
			String opponent = gameItem.split(" ")[1];

			controls.openGame(opponent);
		}
	}

    // Variables declaration - do not modify                     
    private javax.swing.JLabel UserOptionsLabel;
    private javax.swing.JLabel avatarLabel;
    private javax.swing.JLabel bannerLabel;
    private javax.swing.JButton friendsButton;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel numLossesLabel;
    private javax.swing.JLabel numWinsLabel;
    private javax.swing.JButton saveButton;
    private javax.swing.JTextPane userDescriptionTextPane;
    private javax.swing.JTextField userEmailTextField;
    private javax.swing.JList userGameList;
    private javax.swing.JPanel userInfoPanel;
    private javax.swing.JLabel usernameLabel;
    // End of variables declaration                   

}
